<script setup>
import { ref } from 'vue';
import useUserInfoStore from '@/stores/userinfo.js';
import { updatePwdService } from "@/api/user.js";
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const userInfoStore = useUserInfoStore();
const router = useRouter();

const userInfo = ref({ ...userInfoStore.info });

const rules = {
    old_pwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        {
            pattern: /^\S{2,10}$/,
            message: '密码必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        {
            pattern: /^\S{2,10}$/,
            message: '密码必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
    re_pwd: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            pattern: /^\S{2,10}$/,
            message: '密码必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
};

const updatePwd = async () => {
    try {
        const result = await updatePwdService(userInfo.value);
        ElMessage.success(result.msg ? result.msg : "修改成功");
        router.push('/');
    } catch (error) {
        ElMessage.error("更新失败，请稍后再试");
    }
};
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原密码" prop="old_pwd">
                        <el-input type="password" v-model="userInfo.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input type="password" v-model="userInfo.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="re_pwd">
                        <el-input type="password" v-model="userInfo.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updatePwd">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>